#!/bin/sh
#desc:Motion detection

CFGPATH="/etc/opendomo/video"
CFG_COMMON="/etc/opendomo/video/common.conf"
PID="/var/run/motion_ai.pid"
BINARY="/usr/bin/motion_detection"

. "$CFG_COMMON"
start(){
  echo -n "Starting motion detection..."
  # Omitimos los archivos que no sean ".conf"
  
  for i in `ls $CFGPATH/*.conf 2>/dev/null | grep -v common.conf`; do
	if test -f $i; then
		# 1. Cargamos configuración
		. $i
		cam_name=`basename "$i" | cut -d"." -f1`	
		zones_coords=""
		# zones are loaded
		for i in `seq 1 5`; do
			var_name="\$AREA"_"$i"_"X1"
			zone_x1="`eval echo $var_name`"
			var_name="\$AREA"_"$i"_"Y1"
			zone_y1="`eval echo $var_name`"
			var_name="\$AREA"_"$i"_"X2"
			zone_x2="`eval echo $var_name`"
			var_name="\$AREA"_"$i"_"Y2"
			zone_y2="`eval echo $var_name`"
		
			if [ "$zone_x1" != "" ] && [ "$zone_x2" != "" ]; then
				zones_coords="$zone_x1-$zone_y1-$zone_x2-$zone_y2 $zones_coords"
			fi	
		done		
		
		# If there is not sensitivity
		if [ "$SENSITIVITY" = "" ]; then
			SENSITIVITY="200"
		fi
		
		if test -x $BINARY; then
			if test `whoami` == "root"; then
				su -c "$BINARY \"$URL\" \"$AUTH\" \"$TARGET_DIR/$cam_name\" \"$SENSITIVITY\" \"$zones_coords\" 2>/dev/null" admin &
			else
				$BINARY "$URL" "$AUTH" "$TARGET_DIR/$cam_name" "$SENSITIVITY" \"$zones_coords\" 2>/dev/null &
			fi		
		fi
	fi
  done

  #TODO: de momento no tenemos PID
  touch $PID
  chown admin $PID 2>/dev/null
  chmod g+rw $PID 2>/dev/null
}

stop(){
  echo -n "Stopping motion detection..."
  killall "motion_detection" 2>/dev/null
  rm -fr $PID
}


case "$1" in
  start)
  	start
	;;
  stop)
  	stop
	;;
  status)
  	if test -f $PID; then
  		echo "The service is running"
  		exit 0
  	else
  		echo "Service not started"
  		exit 1
  	fi
        ;;
  reload|restart)
  	stop
  	start
	;;
  *)
	echo $"Usage: $0 {start|stop|restart|status}"
	exit 1
esac
